﻿using System;
using System.Collections.Generic;

namespace FlashPay.Admin.Controllers
{
    using FlashPay.Entity;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Request.Payment;
    using FlashPay.Entity.Response.AdjustBalance;
    using FlashPay.Entity.Response.Payment;
    using FlashPay.Entity.Response.User;
    using FlashPay.Service.Interface;
    using FlashPay.Util;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using OfficeOpenXml;
    using System.IO;
    using System.Linq;

    /// <summary>
    /// 付款控制器
    /// </summary>
    /// <remarks>2018-08-27 immi 创建</remarks>
    public class PaymentController : BaseController
    {
        #region 注入
        /// <summary>
        /// 余额变化业层接口
        /// </summary>
        private readonly AdjustBalanceService _adjustBalanceService;

        /// <summary>
        /// 付款记录业务接口
        /// </summary>
        private readonly PaymentRecordService _paymentRecordService;

        /// <summary>
        /// 实际付款记录业务接口
        /// </summary>
        private readonly RecordRealService _recordRealService;

        /// <summary>
        /// 用户业务接口
        /// </summary>
        private readonly BankService _bankService;

        /// <summary>
        /// 日志业务接口
        /// </summary>
        private readonly LogService _logService;

        /// <summary>
        /// 
        /// </summary>
        private IHostingEnvironment _hostingEnv;

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="_manage"></param>
        /// <param name="paymentRecordService">余额变化业层接口</param>
        /// <param name="adjustBalanceService">付款记录业务接口</param>
        /// <param name="recordRealService">实际付款记录业务接口</param>
        public PaymentController(IAuthenticate<TicketResponse> _manage, IHttpContextAccessor _accessor, PaymentRecordService paymentRecordService, AdjustBalanceService adjustBalanceService, RecordRealService recordRealService, BankService bankService, LogService logService, IHostingEnvironment env) : base(_manage, _accessor)
        {
            _paymentRecordService = paymentRecordService;
            _adjustBalanceService = adjustBalanceService;
            _recordRealService = recordRealService;
            _bankService = bankService;
            _logService = logService;
            _hostingEnv = env;
        }
        #endregion

        #region 付款卡
        /// <summary>
        /// 付款卡管理
        /// </summary>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentCard0001)]
        public JsonResult PaymentCardPager(PaymentCardQuery query)
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }
            query.CompanyId = ticketResponse.CompanyID;
            query.UserPermission = ticketResponse.UserPermission;
            query.PlatformType = ticketResponse.PlatformType;
            var list = _paymentRecordService.GetPaymentCardPager(query);
            return Json(list);
        }

        /// <summary>
        /// 获取付款卡
        /// </summary>
        /// <param name="bcId">银行卡编号</param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.PaymentCard0002)]
        public JsonResult GetPaymentCard(int bcId)
        {
            var response = _bankService.Get(_manage.data.CompanyID, bcId,_manage.data.UserPermission);
            
            return Json(response);
        }

        /// <summary>
        /// 付款卡编辑
        /// </summary>
        /// <param name="bcId">银行卡编号</param>
        [AuthorizeFilter(AuthCode.PaymentCard0002)]
        public JsonResult PaymentCardEdit(PaymentCardEditRequest request)
        {
            request.UserPermission = _manage.data.UserPermission;
            var response = _bankService.PaymentCardEdit(request);

            return Json(response);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.PaymentCard0003)]
        public JsonResult PaymentCardUpdateStatus(int id, SByte status)
        {
            //输出
            var response = new JResult()
            {
                Success = false
            };

            //银行卡状态
            var enableStatus = new List<sbyte>()
            {
                (sbyte)EnableStatus.有效.GetHashCode(),
                (sbyte)EnableStatus.禁用.GetHashCode()
            };

            //验证参数是否包含在数组中
            if (enableStatus.Contains(status))
            {
                response = _bankService.UpdateEnableStatus(id, status, _manage.data.UserName);
            }
            else
            {
                response.ErrorMessage = "参数错误！";
            }


            return Json(response);
        }

        /// <summary>
        /// 银行卡余额异常查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.PaymentCard0005)]
        public JsonResult PaymentcardException(PaymentcardExceptionRequest request)
        {
            var response = _paymentRecordService.GetPaymentcardException(request);
            return Json(response);
        }

        /// <summary>
        /// 更新AdjustBalanceRID
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.PaymentCard0005)]
        public JsonResult UpdateAdjustBalanceRID(long rid)
        {
            var response = _bankService.UpdateAdjustBalanceRID(rid);
            return Json(response);
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        public JsonResult UploadFiles()
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                // 文件大小

                if (Request.Form.Files.Count == 0)
                {
                    throw new Exception("未检测到文件");
                }

                var files = Request.Form.Files;

                foreach (var file in files)
                {
                    //扩展名
                    var extensionName = Path.GetExtension(file.FileName);
                    // 原文件名（包括路径）
                    var fileName = Path.Combine("uploadfiles", Guid.NewGuid().ToString("N") + extensionName);
                    //创建文件夹
                    if (!Directory.Exists(_hostingEnv.WebRootPath + @"\uploadfiles"))
                        Directory.CreateDirectory(_hostingEnv.WebRootPath + @"\uploadfiles");
                    //物理路径
                    string savePath = Path.Combine(_hostingEnv.WebRootPath, fileName);
                    //保存文件
                    using (FileStream fs = new FileStream(savePath, FileMode.CreateNew))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                }

                //var file = Request.Form.Files[0];

                //格式限制
                //var allowType = new string[] { "image/jpg", "image/png" };

            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }
        #endregion

        #region 付款记录
        /// <summary>
        /// 付款记录
        /// </summary>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0001)]
        public JsonResult GetPaymentRecords(PaymentRecordQuery query)
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }

            query.DepositOrPaymentType = DepositOrPaymentType.付款;

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {

                    var startTime = Convert.ToDateTime(query.StartTime);
                    var endTime = Convert.ToDateTime(query.EndTime);

                    //query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd 00:00:00");
                    //query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd 23:59:59");

                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            }
            //query.CompanyId = _manage.data.CompanyID;
            //query.UserPermission = _manage.data.UserPermission;

            query.CompanyId = ticketResponse.CompanyID;
            query.UserPermission = ticketResponse.UserPermission;
            var list = _paymentRecordService.GetPaymentRecordPager(query);
            return Json(list);
        }

        private bool IsDate(string date)
        {
            try
            {
                DateTime.Parse(date);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 付款记录(新增按钮)
        /// </summary>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0001)]
        public JsonResult PaymentRecordAddAuth()
        {
            var response = new JResult() {
                Success = true
            };

            try{
                var userPermission = _manage.data.UserPermission;
                if (userPermission.Contains("PaymentRecord0002")) {
                    response.StatusCode = "PaymentRecord0002";
                }

                if (userPermission.Contains("PaymentRecord0011"))
                {
                    response.ErrorCode = "PaymentRecord0011";
                }
            }
            catch (Exception ex) {
                response.Success = false;
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }

        /// <summary>
        /// 获取第三方支付类型
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0001)]
        public JsonResult GetSysConfig()
        {
            var list = _paymentRecordService.GetSysConfigList();
            return Json(list);
        }

        /// <summary>
        /// 获取付款记录
        /// </summary>
        /// <param name="request"></param>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0002)]
        public JsonResult GetPaymentRecord(PaymentCardRequest request)
        {
            var response = new JResult<PaymentCardResponse>()
            {
                Success = true
            };

            request.CompanyId = _manage.data.CompanyID;

            var paymentRecord = _paymentRecordService.GetPaymentCard(request);
            if (paymentRecord != null)
            {
                response.Data = paymentRecord;
            }

            return Json(response);
        }

        /// <summary>
        /// 新增付款卡
        /// </summary>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0002)]
        public JsonResult PaymentRecordAdd(PaymentRecordAddRequest request)
        {
            request.CurrentCompanyId = _manage.data.CompanyID;
            request.DepositType = "A";
            request.CreateName = _manage.data.UserName;
            request.Ip = _accessor.HttpContext.GetUserIp();
            var response = _paymentRecordService.PaymentRecordAdd(request);

            return Json(response);
        }

        /// <summary>
        /// 付款记录取消
        /// </summary>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0004)]
        public JsonResult PaymentRecordCancel(long orderNo)
        {
            //验证订单
            var response = _paymentRecordService.PaymentRecordCancel(orderNo, _manage.data.UserName);
            return Json(response);
        }

        /// <summary>
        /// 付款记录重置
        /// </summary>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0003)]
        public JsonResult PaymentRecordReset(long orderNo)
        {
            //验证订单
            var response = _paymentRecordService.PaymentRecordReset(orderNo, _manage.data.UserName);
            return Json(response);
        }

        /// <summary>
        /// 获取付款记录的真实付款记录
        /// </summary>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0005)]
        public JsonResult PaymentRecordReals(long orderNo,int minutes)
        {

            var response = new PaymentRecordRealResult<List<PaymentRecordRealResponse>>()
            {
                Success = true
            };

            if (minutes < 1 || minutes > 1440)
            {
                response.Success = false;
                response.ErrorMessage = "匹配时间(分)介于 1 和 1440 之间";
                return Json(response);
            }

            var query = new PaymentRecordRealQuery() {
                OrderNo = orderNo,
                Minutes = minutes,
                UserPermission = _manage.data.UserPermission,
                PlatformType = _manage.data.PlatformType
            };

            response = _recordRealService.GetPaymentRecordReals(query);

            return Json(response);
        }

        /// <summary>
        /// 转成功
        /// </summary>
        /// <param name="reqeust">参数</param>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0006)]
        public JsonResult TurnSuccess(TurnReqeust reqeust)
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }

            reqeust.UserId = ticketResponse.UserID;
            reqeust.UserName = ticketResponse.UserName;
            var response = _recordRealService.TurnSuccess(reqeust);
            return Json(response);
        }

        /// <summary>
        /// 转成功
        /// </summary>
        /// <param name="reqeust">参数</param>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0006)]
        public JsonResult EmptyRecordTurnSuccess(TurnReqeust reqeust)
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }

            reqeust.UserId = ticketResponse.UserID;
            reqeust.UserName = ticketResponse.UserName;
            var response = _recordRealService.EmptyRecordTurnSuccess(reqeust);
            return Json(response);
        }

        /// <summary>
        /// 转失败
        /// </summary>
        /// <param name="reqeust">参数</param>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0006)]
        public JsonResult TurnFailure(TurnReqeust reqeust)
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }
            //验证订单
            reqeust.UserId = ticketResponse.UserID;
            reqeust.UserName = ticketResponse.UserName;
            var response = _recordRealService.TurnFailure(reqeust);
            return Json(response);
        }

        /// <summary>
        /// 付款确认(获取付款记录)
        /// </summary>
        /// <param name="request">参数</param>
        [AuthorizeFilter(AuthCode.PaymentRecord0008)]
        public JsonResult GetPaymentConfirmRecord(long id)
        {
            var response = new JResult<RecordRealResponse>() {
                Success = false
            };

            response.Data = _paymentRecordService.Get(id);
            response.Success = true;

            return Json(response);
        }

        /// <summary>
        /// 付款确认
        /// </summary>
        /// <param name="request">参数</param>
        [AuthorizeFilter(AuthCode.PaymentRecord0008)]
        public JsonResult PaymentConfirm(long orderNo)
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }
            //验证订单
            var request = new PaymentConfirmRequest()
            {
                OrderNo = orderNo,
                ConfirmUID = ticketResponse.UserID,
                ConfirmName = ticketResponse.UserName,
                Ip = _accessor.HttpContext.GetUserIp()
            };

            var response = _paymentRecordService.PaymentConfirm(request);

            return Json(response);
        }

        /// <summary>
        /// 重新配卡
        /// </summary>
        /// <returns></returns>
        public JsonResult GetRenewMatchCardOrder(long id)
        {
            var response = new JResult<RecordRealResponse>()
            {
                Success = false
            };

            response.Data = _paymentRecordService.Get(id);
            response.Success = true;

            return Json(response);
        }

        /// <summary>
        /// 获取付款卡
        /// </summary>
        /// <param name="query"></param>
        [AuthorizeFilter(AuthCode.PaymentRecord0009)]
        public JsonResult CompanyPaymentCard(RenewMatchCardQuery query)
        {
            query.CompanyId = _manage.data.CompanyID;
            query.UserPermission = _manage.data.UserPermission;
            query.EnableStatus = (sbyte)EnableStatus.有效.GetHashCode();
            var list = _paymentRecordService.GetRenewMatchCardPager(query);
            return Json(list);
        }

        /// <summary>
        /// 重新配卡
        /// </summary>
        /// <param name="request">参数</param>
        [AuthorizeFilter(AuthCode.PaymentRecord0009)]
        public JsonResult RenewMatchCard(RenewMatchCardReqeust reqeust)
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }
            //验证订单
            var request = new RenewMatchCardReqeust()
            {
                PaymentRecordId = reqeust.PaymentRecordId,
                PaymentCardId = reqeust.PaymentCardId,
                OriginalPaymentCardId = reqeust.OriginalPaymentCardId,
                UserId = ticketResponse.UserID,
                CompanyId = ticketResponse.CompanyID,
                UserName = ticketResponse.UserName,
                Ip = _accessor.HttpContext.GetUserIp()
            };

            var response = _paymentRecordService.RenewMatchCard(request);

            return Json(response);
        }

        /// <summary>
        /// 重新付款
        /// </summary>
        /// <param name="request">参数</param>
        [AuthorizeFilter(AuthCode.PaymentRecord0010)]
        public JsonResult RenewPayment(RenewPaymentRequest request)
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }

            request.UserId = ticketResponse.UserID;
            request.UserName = ticketResponse.UserName;
            request.CompanyId = ticketResponse.CompanyID;
            request.Ip = _accessor.HttpContext.GetUserIp();
            var response = _paymentRecordService.RenewPayment(request);

            return Json(response);
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="request">参数</param>
        [AuthorizeFilter(AuthCode.PaymentRecord0011)]
        public IActionResult PaymentRecordExport(PaymentRecordQuery query)
        {
            var response = new JResult<List<PaymentRecordExportResponse>>() {
                Success = false
            };
            query.Page = 1;
            query.Rows = 100000;

            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }

            query.DepositOrPaymentType = DepositOrPaymentType.付款;

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {

                    var startTime = Convert.ToDateTime(query.StartTime);
                    var endTime = Convert.ToDateTime(query.EndTime);

                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            }

            query.CompanyId = ticketResponse.CompanyID;
            query.UserPermission = ticketResponse.UserPermission;

            try
            {
                var list = _paymentRecordService.GetPaymentRecordExport(query);
                if (list.Rows == null && list.Rows.Any()) {
                    throw new Exception("付款记录为空！");
                }

                var paymentRecordExportResponse = new List<PaymentRecordExportResponse>();
                paymentRecordExportResponse.Add(new PaymentRecordExportResponse() {
                    OrderNo = "订单号",
                    CompanyName = "公司名称",
                    WithdrawalOrderNo = "客户单号",
                    BankName = "付款银行",
                    CardName = "付款姓名",
                    CardNumber = "付款卡号",
                    WithdrawalAmount = "付款金额",
                    WithdrawalFee = "手续费",
                    CreateDbdate = "创建时间",
                    PaymentStatus = "付款结果",
                    WithdrawalAccountName = "客户姓名",
                    WithdrawalBankName = "客户银行",
                    WithdrawalCardNumber = "客户卡号",
                    PaymentDate = "付款时间",
                    DepositType = "付款等级",
                    NoticeStatus = "通知状态",
                    NoticeLastDate = "通知时间",
                    NoticeTimes = "通知次数",
                    PaymentType = "付款类型"
                });
                foreach (var item in list.Rows)
                {
                    paymentRecordExportResponse.Add(new PaymentRecordExportResponse()
                    {
                        OrderNo = "'"+item.OrderNo,
                        CompanyName = item.CompanyName,
                        WithdrawalOrderNo = item.WithdrawalOrderNo,
                        BankName = item.BankName,
                        CardName = item.CardName,
                        CardNumber = item.CardNumber,
                        WithdrawalAmount = item.WithdrawalAmount,
                        WithdrawalFee = item.WithdrawalFee,
                        CreateDbdate = item.CreateDbdate.HasValue ? item.CreateDbdate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        PaymentStatus = PaymentStatus(item.PaymentStatus, item.PaymentFailInfo),
                        WithdrawalAccountName = item.WithdrawalAccountName,
                        WithdrawalBankName = item.WithdrawalBankName,
                        WithdrawalCardNumber = "'" + item.WithdrawalCardNumber,
                        PaymentDate = item.PaymentDate.HasValue ? item.PaymentDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        DepositType = item.DepositType,
                        NoticeStatus = NoticeStatus(item.NoticeStatus),
                        NoticeLastDate = string.IsNullOrEmpty(item.NoticeLastDate)? "": item.NoticeLastDate,
                        NoticeTimes = item.NoticeTimes.HasValue ? item.NoticeTimes.Value.ToString() : "0",
                        PaymentType = item.PaymentTypeName
                    });
                }

                response.Success = true;
                response.Data = paymentRecordExportResponse;
                response.StatusCode = $"付款记录({query.StartTime}-{query.EndTime})";
                response.SuccessMessage = "生成付款记录成功！";
            }
            catch (Exception ex) {
                response.SuccessMessage = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 付款状态
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        private string PaymentStatus(sbyte status,string message)
        {
            var result = "";

            switch (status)
            {
                case 1:
                    result = "未付款";
                    break;
                case 2:
                    result = $"<span style=color:#3e8f3e>付款成功</span> {message}";
                    break;
                case 3:
                    result = $"<span style=color:#FF0000>付款失败</span>  {message}";
                    break;
                case 4:
                    result = $"付款中 {message}";
                    break;
                case 5:
                    result = "取消付款";
                    break;
                case 6:
                    result = "推送异常";
                    break;
            }

            return result;
        }

        /// <summary>
        ///  通知状态
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        private string NoticeStatus(int status)
        {
            var result = "";

            switch (status)
            {
                case 1:
                    result = "未通知";
                    break;
                case 2:
                    result = "<span style=color:#3e8f3e>通知成功</span>";
                    break;
                case 3:
                    result = "<span style=color:#FF0000>通知失败</span>";
                    break;
                case 4:
                    result = "通知中";
                    break;
            }

            return result;
        }


        /// <summary>
        /// 付款记录（日志）
        /// </summary>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentRecord0001)]
        public JsonResult PaymentRecordsLog(GetListByOrderNoQuery query)
        {
            query.LogTypes = new List<int>()
            {
                (int)LogRecordLogType.PaymentRecord_Audit,(int)LogRecordLogType.PaymentRecord_Reject,(int)LogRecordLogType.PaymentRecord_Reject_Auto
            };
            var response = _logService.GetListByOrderNo(query);

            return Json(response);
        }

        /// <summary>
        /// 改变渠道
        /// </summary>
        /// <param name="request"></param>
        [AuthorizeFilter(AuthCode.PaymentRecord0014)]
        public JsonResult ChangeChannels(ChangeChannelsRequest request)
        {
            var response = _paymentRecordService.ChangeChannels(request);

            return Json(response);
        }

        /// <summary>
        /// 改变公司
        /// </summary>
        /// <param name="request"></param>
        [AuthorizeFilter(AuthCode.PaymentRecord0015)]
        public JsonResult ChangeCompany(ChangeCompanyRequest request)
        {
            request.LoginCompanyId = _manage.data.CompanyID;
            var response = _paymentRecordService.ChangeCompany(request);


            return Json(response);
        }
        #endregion

        #region 实际付款记录
        /// <summary>
        /// 实际付款记录
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.RecordReal0001)]
        public JsonResult RecordReal(RecordRealQuery query)
        {
            query.RecordType = (int)AdjustStatus.付款;
            return CommonReal(query);
        }

        //公共方法
        private JsonResult CommonReal(RecordRealQuery query)
        {
            var response = new JResult()
            {
                Success = false
            };
            var now = DateTime.Now;
            //本月的第一天
            var firstDay = new DateTime(now.Year, now.Month, 1);
            //本月的最后一天
            var lastDay = now.AddDays(1 - now.Day).AddMonths(1).AddDays(-1);

            query.RecordType = query.RecordType;

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (WebUtil.IsDate(query.StartTime) && WebUtil.IsDate(query.EndTime))
                {
                    //TODO 两个时间之差不能大于6个月
                    var startTime = Convert.ToDateTime(query.StartTime);
                    var endTime = Convert.ToDateTime(query.EndTime);
                    if (startTime > endTime)
                    {
                        response.ErrorMessage = "开始时间不能大于结束时间";
                        return Json(response);
                    }
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd 23:59:59");
                }
                else
                {
                    query.StartTime = firstDay.ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = lastDay.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = firstDay.ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = lastDay.ToString("yyyy-MM-dd 23:59:59");
            }
            query.CompanyId = _manage.data.CompanyID;
            var list = _recordRealService.GetPaymentRecordPager(query);
            return Json(list);
        }
        #endregion

        #region 未入账收款纪录
        /// <summary>
        /// 未入账收款纪录
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.ReceiptAccounted0001)]
        public JsonResult ReceiptList(RecordRealQuery query)
        {
            query.RecordType = (int)AdjustStatus.收款;
            return CommonReal(query);
        }

        /// <summary>
        /// 补单
        /// </summary>
        /// <param name="request"></param>
        [AuthorizeFilter(AuthCode.ReceiptAccounted0002)]
        public JsonResult GetReceiptMakeUp(long orderNo)
        {
            var response = _recordRealService.GetByOrderNo(orderNo);
            return Json(response);
        }

        /// <summary>
        /// 补单
        /// </summary>
        /// <param name="request"></param>
        [AuthorizeFilter(AuthCode.ReceiptAccounted0002)]
        public JsonResult ReceiptMakeUp(ReceiptMakeUpRequest request)
        {
            request.UserName = _manage.data.UserName;
            var response = _paymentRecordService.ReceiptMakeUp(request);

            return Json(response);
        }
        #endregion

        #region 付款余额变化表
        /// <summary>
        /// 付款余额变化表
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.PaymentAdjustBalance0001)]
        public JsonResult PaymentAdjustBalance(PaymentAdjustBalanceQuery query)
        {
            var response = new JResult()
            {
                Success = false
            };
            query.AdjustStatus = (sbyte)AdjustStatus.付款.GetHashCode();
            var now = DateTime.Now;
            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = now.ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = now.ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = now.ToString("yyyy-MM-dd 23:59:59");
            }
            query.CompanyId = _manage.data.CompanyID;
            var list = _adjustBalanceService.GetPaymentAdjustBalancePager(query);
            return Json(list);
        }
        #endregion

        #region 收款卡余额变化表
        /// <summary>
        /// 收款余额变化表
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.ReceiptBalance0001)]
        public JsonResult ReceiptAdjustBalance(PaymentAdjustBalanceQuery query)
        {
            var response = new JResult()
            {
                Success = false
            };

            query.AdjustStatus = (sbyte)AdjustStatus.收款.GetHashCode();

            var now = DateTime.Now;
            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = now.ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = now.ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = now.ToString("yyyy-MM-dd 23:59:59");
            }
            query.CompanyId = _manage.data.CompanyID;
            var list = _adjustBalanceService.GetPaymentAdjustBalancePager(query);
            return Json(list);
        }
        #endregion

        #region 中转卡余额变化表
        /// <summary>
        /// 收款余额变化表
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.Transferadjustbalance001)]
        public JsonResult TransferAdjustBalance(PaymentAdjustBalanceQuery query)
        {
            var response = new JResult()
            {
                Success = false
            };

            query.AdjustStatus = (sbyte)AdjustStatus.中转;

            var now = DateTime.Now;
            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = now.ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = now.ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = now.ToString("yyyy-MM-dd 23:59:59");
            }
            query.CompanyId = _manage.data.CompanyID;
            var list = _adjustBalanceService.GetPaymentAdjustBalancePager(query);
            return Json(list);
        }
        #endregion

        #region 余额变化表导出
        /// <summary>
        /// 收款余额变化表
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.PaymentAdjustBalance0001, AuthCode.ReceiptBalance0001,AuthCode.Transferadjustbalance001)]
        public JsonResult AdjustBalanceExport(PaymentAdjustBalanceQuery query)
        {
            var response = new JResult<List<PaymentAdjustBalanceResponse>>()
            {
                Success = false
            };

            query.CompanyId = _manage.data.CompanyID;

            var now = DateTime.Now;

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = now.ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = now.ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = now.ToString("yyyy-MM-dd 23:59:59");
            }

            try {
                var list = _adjustBalanceService.GetPaymentAdjustBalanceExport(query);
                if (list != null && list.Any())
                {
                    var paymentAdjustBalanceResponse = new List<PaymentAdjustBalanceResponse>();
                    foreach (var item in list)
                    {
                        paymentAdjustBalanceResponse.Add(new PaymentAdjustBalanceResponse()
                        {
                            CompanyName = item.CompanyName,
                            CompanyNameEn = item.CompanyNameEn,
                            BankName = item.BankName,
                            Amount = item.Amount,
                            BeforeBalance = item.BeforeBalance,
                            AfterBalance = item.AfterBalance,
                            CardName = item.CardName,
                            CardNumber = item.CardNumber,
                            CreateName = string.IsNullOrEmpty(item.CreateName) ? "" : item.CreateName,
                            CreateDBDate = item.CreateDBDate,
                            CreateRemark = string.IsNullOrEmpty(item.CreateRemark)?"": item.CreateRemark,
                            AdjustStatus = item.AdjustStatus,
                            AdjustStatusText = GetAdjustStatus(item.AdjustStatus),
                            OrderNo = "'" + item.OrderNo
                        });
                    }
                    response.Data = paymentAdjustBalanceResponse;
                }
                response.StatusCode = $"余额变化表({query.StartTime}-{query.EndTime})";
                response.Success = true;
            }
            catch (Exception ex)
            {
                response.SuccessMessage = ex.Message;
            }

            return Json(response);
        }

        /// <summary>
        /// 余额变化(导帮忙按钮)
        /// </summary>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.PaymentAdjustBalance0001, AuthCode.ReceiptBalance0001, AuthCode.Transferadjustbalance001)]
        public JsonResult AdjustBalanceExportAuth()
        {
            var response = new JResult<AdjustBalanceExportAuth>()
            {
                Success = true,
                Data = new AdjustBalanceExportAuth() { }
            };

            try
            {
                var userPermission = _manage.data.UserPermission;
                //收款
                if (userPermission.Contains("ReceiptBalance0002"))
                {
                    response.Data.ReceiptAdjustBalance = "ReceiptBalance0002";
                }
                //付款
                if (userPermission.Contains("PaymentAdjustBalance0002"))
                {
                    response.Data.PaymentAdjustBalance = "PaymentAdjustBalance0002";
                }
                //中转
                if (userPermission.Contains("Transferadjustbalance002"))
                {
                    response.Data.TransferAdjustBalance = "Transferadjustbalance002";
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }

        /// <summary>
        ///  通知状态
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        private string GetAdjustStatus(sbyte status)
        {
            var result = "";

            switch (status)
            {
                case 1:
                    result = "收款";
                    break;
                case 2:
                    result = "付款";
                    break;
                case 3:
                    result = "中转";
                    break;
                default:
                    result = "无";
                    break;
            }

            return result;
        }
        #endregion

    }
}